import Vue from 'vue'
import Vuex from 'vuex'
import { getUserInfo } from "@/api/login";
import { getToken, removeToken } from '@/utils/token'
import router, { createRouter, adminRoutes, userRoutes } from "@/router";
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo: null,
    isAddRouter: false,
  },
  getters: {
    userInfo: state => state.userInfo
  },
  mutations: {
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_IS_ADD_ROUTER: (state, isAddRouter) => {
      state.isAddRouter = isAddRouter
    }
  },
  actions: {
    GetUserInfo({ commit, state }) {
      return new Promise(resolve => {
        getUserInfo().then(res => {
          let data = res.data.data;
          let routersMap = {
            1: userRoutes,
            2: adminRoutes,
          };
          if (!state.isAddRouter) {
            routersMap[data.power].forEach((route) => router.addRoute(route));
            commit('SET_IS_ADD_ROUTER', true)
          }
          resolve(data);
          commit('SET_USER_INFO', data)
        })
      })
    },
    Logout({ commit }) {
      commit('SET_USER_INFO', null)
      removeToken();
      commit('SET_IS_ADD_ROUTER', false);
      router.matcher = createRouter().matcher;
      router.replace('/login')
    }
  },
  modules: {
  }
})
